package com.wln.kms.kms.controller;

import java.io.UnsupportedEncodingException;
import java.util.*;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wln.kms.kms.config.JwtUtil;
import com.wln.kms.kms.vo.BargainVo;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import com.wln.kms.kms.entity.BargainOrderEntity;
import com.wln.kms.kms.service.BargainOrderService;
import com.wln.common.utils.PageUtils;
import com.wln.common.utils.R;

import javax.servlet.http.HttpServletRequest;


/**
 * @author wulinna
 * @email 2258732595@qq.com
 * @date 2022-03-10 10:47:57
 */
@Controller
@RequestMapping("kms/bargainorder")
public class BargainOrderController {
    @Autowired
    private BargainOrderService bargainOrderService;

    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @ResponseBody
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = bargainOrderService.queryPage(params);

        return R.ok().put("page", page);

    }

    /**
     * 列表
     */
    @RequestMapping("/find")
    @ResponseBody
    public R find(@RequestParam Map<String, Object> params) {
        PageUtils page = bargainOrderService.find(params);

        return R.ok().put("page", page);

    }

    /**
     * 生成分享链接
     */
    @RequestMapping("/getShareUrl/{id}/{userId}")
    @ResponseBody
    public R getShareUrl(@PathVariable("id") String bargainHid,@PathVariable("userId") String userId) {

        String path = jwtUtil.createJWT(userId, bargainHid, "user");
        return R.ok().put("shareUrl", "http://localhost:88/api/kms/bargainorder/" + path + "/bargaining");

    }

    //进行砍价
    @RequestMapping("/{path}/bargaining/{bargainId}")
    public String bargaining(@PathVariable("path") String path, HttpServletRequest request, @PathVariable("bargainId") String bargainId) {

        Claims claims = jwtUtil.parseJWT(path);
        String id = claims.getId();
        return "redirect:http://seckill.com:8081/#/find?1=1&bargainId="+bargainId+"&userid="+id;
    }


    @RequestMapping("/success")
    public String success(HttpServletRequest request) throws UnsupportedEncodingException, AlipayApiException {
        //获取支付宝GET过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        System.out.println(params);

        boolean signVerified = AlipaySignature.rsaCheckV2(params, com.alipay.config.AlipayConfig.alipay_public_key, com.alipay.config.AlipayConfig.charset, com.alipay.config.AlipayConfig.sign_type); //调用SDK验证签名
        String s = params.get("out_trade_no");


        //——请在这里编写您的程序（以下代码仅作参考）——
        if (signVerified) {
            System.out.println("abcabcabcabcabc");
        } else {

        }
        //——请在这里编写您的程序（以上代码仅作参考）——
        return "redirect:http://seckill.com:8081/#/orderinfo";
    }


    /**
     * 列表
     */
    @RequestMapping("/topay")
    @ResponseBody
    public String topay(@RequestParam("id") long id) throws AlipayApiException {
        BargainOrderEntity byId = bargainOrderService.getOne(new QueryWrapper<BargainOrderEntity>().eq("horder_id", id));
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(com.alipay.config.AlipayConfig.gatewayUrl, com.alipay.config.AlipayConfig.app_id, com.alipay.config.AlipayConfig.merchant_private_key, "json", com.alipay.config.AlipayConfig.charset, com.alipay.config.AlipayConfig.alipay_public_key, com.alipay.config.AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(com.alipay.config.AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(com.alipay.config.AlipayConfig.notify_url);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = id + "";
        //付款金额，必填
        String total_amount = byId.getHorderPrice() + "";
        //订单名称，必填
        String subject = byId.getGoodsName();
        //商品描述，可空
        String body = "";

        alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                + "\"total_amount\":\"" + total_amount + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"body\":\"" + body + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        //若想给BizContent增加其他可选请求参数，以增加自定义超时时间参数timeout_express来举例说明
        //alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
        //		+ "\"total_amount\":\""+ total_amount +"\","
        //		+ "\"subject\":\""+ subject +"\","
        //		+ "\"body\":\""+ body +"\","
        //		+ "\"timeout_express\":\"10m\","
        //		+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        //请求参数可查阅【电脑网站支付的API文档-alipay.trade.page.pay-请求参数】章节

        //请求
        String result = alipayClient.pageExecute(alipayRequest).getBody();

        return result;
    }


    /**
     * 信息
     */
    @RequestMapping("/launch")
    @ResponseBody
    public R launch(@RequestBody BargainOrderEntity bargainOrder) {
        R add = bargainOrderService.add(bargainOrder);
        return add;
    }

    /**
     * 帮砍
     */
    @RequestMapping("/cut/{userid}")
    @ResponseBody
    public R cut(@RequestBody BargainOrderEntity bargainOrder,@PathVariable("userid")String userid) {
        R add = bargainOrderService.cut(bargainOrder,userid);
        return add;
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{horderId}")
    @ResponseBody
    public R info(@PathVariable("horderId") Long horderId) {
        BargainOrderEntity bargainOrder = bargainOrderService.getById(horderId);

        return R.ok().put("bargainOrder", bargainOrder);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @ResponseBody
    public R save(@RequestBody BargainOrderEntity bargainOrder) {
        bargainOrderService.save(bargainOrder);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @ResponseBody
    public R update(@RequestBody BargainOrderEntity bargainOrder) {
        bargainOrderService.updateById(bargainOrder);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @ResponseBody
    public R delete(@RequestBody Long[] horderIds) {
        bargainOrderService.removeByIds(Arrays.asList(horderIds));

        return R.ok();
    }

}
